#include "initrecordertask.h"
#include "captchaassistdialog.h"
#include "libs/controls/toastlabel.h"
#include "libs/core/model/attentionmodel.h"
#include "libs/core/model/model.h"
#include "libs/core/model/presentermodel.h"
#include "liveinfoview.h"
#include "liverecorder.h"
#include "livestatusview.h"
#include "liveviewmanager.h"
#include "livewindow.h"
#include "presentermonitor.h"
#include "yingce.h"
#include "yingcewindow.h"
#include <QMessageBox>
#include <QTimer>

InitRecorderTask::InitRecorderTask(LiveRecorder* recorder, QObject* parent)
    : yc::Task { 0, true, 0, parent }, recorder_(recorder)
{
}

void InitRecorderTask::startImpl()
{
    bool kuaishow_found = false;
    auto am = YingCe::instance()->model()->attentionModel();
    auto pm = YingCe::instance()->model()->presenterModel();
    for (auto i : am->attentions()) {
        if (auto p = pm->presenter(i->presenter)) {
            if (p->platform == yc::KUAISHOW_PLATFORM_TYPE) {
                kuaishow_found = true;
                break;
            }
        }
    }
    if (kuaishow_found) {
        auto ret = QMessageBox::question(
                YingCeWindow::instance(), tr("Captcha Assist"),
                tr("To ensure the security of your visit, a slider verification needs to be "
                   "completed. After clicking 'Ok', the Kuaishou verification page will "
                   "automatically open. You just need to "
                   "drag the slider to complete the verification. There is no need to log in to "
                   "your account. Thank you for your cooperation!"),
                QMessageBox::Ok | QMessageBox::Close, QMessageBox::Ok);
        if (ret == QMessageBox::Ok) {
            auto win = recorder_->liveViewManager()->window();
            dialog_ = new CaptchaAssistDialog(win, YingCeWindow::instance());
            const auto rc = YingCeWindow::instance()->geometry();
            const int x = rc.left() + (rc.width() - 480) / 2;
            const int y = rc.top() + (rc.height() - 720) / 2;
            dialog_->setGeometry(x, y, 480, 720);
            dialog_->setWindowModality(Qt::ApplicationModal);
            dialog_->show();

            connect(dialog_.get(), &CaptchaAssistDialog::discarded, this,
                    &InitRecorderTask::terminate);

            reload_timer_ = new QTimer(this);
            reload_timer_->setInterval(5000);
            reload_timer_->setSingleShot(true);
            connect(reload_timer_, &QTimer::timeout, this, &InitRecorderTask::startNext);

            recorder_->monitor()->stop();

            success_count_ = 0;
            pos_ = -1;
            captcha_shown_ = false;
            reload_count_ = 0;
            startNext();
            return;
        }
    }
    Q_EMIT finished();
}

void InitRecorderTask::terminateImpl()
{
    if (reload_timer_) {
        reload_timer_->stop();
    }
}

void InitRecorderTask::startNext()
{
    auto win = recorder_->liveViewManager()->window();
    if (++pos_ >= win->views().size()) {
        dialog_->deleteLater();
        yc::ToastLabel::showMessage(
                tr("Verification has been completed. Please continue to use it."),
                YingCeWindow::instance());
        recorder_->monitor()->start();
        Q_EMIT finished();
    } else {
        win->setCurrent(pos_);
        auto view = win->views().at(pos_);
        if (auto info_view = qobject_cast<LiveInfoView*>(view)) {
            connect(info_view, &LiveInfoView::captchaRequested, this, &InitRecorderTask::showToast);
            info_view->getLiveInfo(0, yc::KUAISHOW_PLATFORM_TYPE, "3x7cff8hm8b9uwi",
                                   LiveHandler(this, [this](int presenter, const QString& args) {
                                       Q_UNUSED(presenter)
                                       Q_UNUSED(args)
                                       if (isRunning()) {
                                           if (!captcha_shown_ && ++reload_count_ < 10) {
                                               // 如果未出现验证码，5秒后重刷
                                               --pos_;
                                               reload_timer_->start();
                                           } else {
                                               ++success_count_;
                                               captcha_shown_ = false;
                                               reload_count_ = 0;
                                               startNext();
                                           }
                                       }
                                   }));
        } else if (auto status_view = qobject_cast<LiveStatusView*>(view)) {
            connect(status_view, &LiveStatusView::captchaRequested, this,
                    &InitRecorderTask::showToast);
            status_view->getLiveStatus(
                    0, yc::KUAISHOW_PLATFORM_TYPE, "3x7cff8hm8b9uwi",
                    LiveHandler(this, [this](int presenter, const QString& args) {
                        Q_UNUSED(presenter)
                        Q_UNUSED(args)
                        if (isRunning()) {
                            startNext();
                        }
                    }));
        }
    }
}

void InitRecorderTask::showToast()
{
    captcha_shown_ = true;
    auto win = recorder_->liveViewManager()->window();
    yc::ToastLabel::showMessage(tr("Please complete the verification assistance (%1/%2).")
                                        .arg(pos_)
                                        .arg(win->views().size()),
                                dialog_);
}
